/*
  Copyright 2011 fullkawa

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package jp.fullkawa.ksp2html;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import jp.fullkawa.ksp.KspFile;
import jp.fullkawa.ksp2html.exception.NotificationException;
import jp.fullkawa.xnovel.XNovel;

public class Ksp2Html
{
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		KspFile ksp = new KspFile(args[0]);

		BufferedReader reader = null;
		try {
			String work_name = ksp.getName().substring(0, ksp.getName().length() - ".ksp".length());

			KspParser.init(work_name);
			String html_file_name = work_name + File.separator + "index.html";

			FileOutputStream html_file_output = new FileOutputStream(html_file_name);
			OutputStreamWriter html_writer = new OutputStreamWriter(html_file_output, "UTF-8");
			reader = ksp.getReader();
			XNovel xnovel = KspParser.parseToXNovel(reader);
			xnovel.setTitle(work_name);

			Writer writer = HTMLBuilder.getXNovelWriter(xnovel, html_writer);
			// System.out.println(writer.toString());

			try {
				writer.flush();
			}
			catch (IOException e1) {
				e1.printStackTrace();
			}
			finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
		}
		catch (NotificationException e) {
			System.out.println(e.getMessage());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
